package com.datagateway.controller;

import com.datagateway.component.DataFormatConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 数据格式转换控制器
 * 提供数据格式转换相关的REST API接口
 * 
 * @author Data Gateway Team
 * @version 1.0.0
 */
@RestController
@RequestMapping("/data-gateway/api/data-format")
public class DataFormatController {

    @Autowired
    private DataFormatConverter dataFormatConverter;

    /**
     * 转换数据格式
     * 
     * @param request 转换请求
     * @return 转换结果
     */
    @PostMapping("/convert")
    public Map<String, Object> convertDataFormat(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String data = (String) request.get("data");
            String inputFormat = (String) request.get("inputFormat");
            String outputFormat = (String) request.get("outputFormat");
            
            if (data == null || inputFormat == null || outputFormat == null) {
                result.put("success", false);
                result.put("message", "缺少必要参数: data, inputFormat, outputFormat");
                return result;
            }
            
            DataFormatConverter.ConversionResult conversionResult = dataFormatConverter.convert(data, inputFormat, outputFormat);
            
            result.put("success", conversionResult.isSuccess());
            result.put("data", conversionResult.getData());
            result.put("status", conversionResult.getStatus());
            result.put("errorMessage", conversionResult.getErrorMessage());
            result.put("inputFormat", inputFormat);
            result.put("outputFormat", outputFormat);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "数据格式转换异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 批量转换数据格式
     * 
     * @param request 批量转换请求
     * @return 转换结果列表
     */
    @PostMapping("/batch-convert")
    public Map<String, Object> batchConvertDataFormat(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            @SuppressWarnings("unchecked")
            List<String> dataList = (List<String>) request.get("dataList");
            String inputFormat = (String) request.get("inputFormat");
            String outputFormat = (String) request.get("outputFormat");
            
            if (dataList == null || inputFormat == null || outputFormat == null) {
                result.put("success", false);
                result.put("message", "缺少必要参数: dataList, inputFormat, outputFormat");
                return result;
            }
            
            List<DataFormatConverter.ConversionResult> conversionResults = dataFormatConverter.batchConvert(dataList, inputFormat, outputFormat);
            
            result.put("success", true);
            result.put("results", conversionResults);
            result.put("count", conversionResults.size());
            result.put("inputFormat", inputFormat);
            result.put("outputFormat", outputFormat);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量数据格式转换异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 验证数据格式
     * 
     * @param request 验证请求
     * @return 验证结果
     */
    @PostMapping("/validate")
    public Map<String, Object> validateDataFormat(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String data = (String) request.get("data");
            String format = (String) request.get("format");
            
            if (data == null || format == null) {
                result.put("success", false);
                result.put("message", "缺少必要参数: data, format");
                return result;
            }
            
            DataFormatConverter.ValidationResult validationResult = dataFormatConverter.validate(data, format);
            
            result.put("success", true);
            result.put("valid", validationResult.isValid());
            result.put("status", validationResult.getStatus());
            result.put("errorMessage", validationResult.getErrorMessage());
            result.put("format", format);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "数据格式验证异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取支持的格式列表
     * 
     * @return 支持的格式列表
     */
    @GetMapping("/supported-formats")
    public Map<String, Object> getSupportedFormats() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<String> supportedFormats = dataFormatConverter.getSupportedFormats();
            
            result.put("success", true);
            result.put("supportedFormats", supportedFormats);
            result.put("count", supportedFormats.size());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取支持的格式列表异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取支持的转换器列表
     * 
     * @return 支持的转换器列表
     */
    @GetMapping("/supported-converters")
    public Map<String, Object> getSupportedConverters() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<String> supportedConverters = dataFormatConverter.getSupportedConverters();
            
            result.put("success", true);
            result.put("supportedConverters", supportedConverters);
            result.put("count", supportedConverters.size());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取支持的转换器列表异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 注册自定义转换器
     * 
     * @param request 注册请求
     * @return 操作结果
     */
    @PostMapping("/converters")
    public Map<String, Object> registerConverter(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String key = (String) request.get("key");
            String converterClass = (String) request.get("converterClass");
            
            if (key == null || converterClass == null) {
                result.put("success", false);
                result.put("message", "缺少必要参数: key, converterClass");
                return result;
            }
            
            // 这里需要根据实际情况实现自定义转换器的注册逻辑
            // 由于Java的反射和类加载限制，这里简化处理
            result.put("success", false);
            result.put("message", "自定义转换器注册功能暂未实现");
            result.put("key", key);
            result.put("converterClass", converterClass);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "注册自定义转换器异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 删除转换器
     * 
     * @param key 转换器键
     * @return 操作结果
     */
    @DeleteMapping("/converters/{key}")
    public Map<String, Object> removeConverter(@PathVariable String key) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = dataFormatConverter.removeConverter(key);
            
            result.put("success", success);
            result.put("message", success ? "转换器删除成功" : "转换器删除失败");
            result.put("key", key);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除转换器异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取转换统计信息
     * 
     * @return 统计信息
     */
    @GetMapping("/statistics")
    public Map<String, Object> getConversionStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            DataFormatConverter.ConversionStatistics stats = dataFormatConverter.getStatistics();
            
            result.put("success", true);
            result.put("statistics", stats);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取转换统计异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 设置转换配置
     * 
     * @param request 配置请求
     * @return 操作结果
     */
    @PostMapping("/config")
    public Map<String, Object> setConversionConfiguration(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Boolean enabled = (Boolean) request.get("enabled");
            String defaultInputFormat = (String) request.get("defaultInputFormat");
            String defaultOutputFormat = (String) request.get("defaultOutputFormat");
            Boolean prettyPrint = (Boolean) request.get("prettyPrint");
            Boolean validateInput = (Boolean) request.get("validateInput");
            Boolean validateOutput = (Boolean) request.get("validateOutput");
            Integer maxConversionSize = (Integer) request.get("maxConversionSize");
            
            if (enabled == null || defaultInputFormat == null || defaultOutputFormat == null || 
                prettyPrint == null || validateInput == null || validateOutput == null || maxConversionSize == null) {
                result.put("success", false);
                result.put("message", "缺少必要参数");
                return result;
            }
            
            dataFormatConverter.setConfiguration(enabled, defaultInputFormat, defaultOutputFormat, 
                prettyPrint, validateInput, validateOutput, maxConversionSize);
            
            result.put("success", true);
            result.put("message", "转换配置设置成功");
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "设置转换配置异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取转换配置
     * 
     * @return 配置信息
     */
    @GetMapping("/config")
    public Map<String, Object> getConversionConfiguration() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            DataFormatConverter.ConversionStatistics stats = dataFormatConverter.getStatistics();
            
            Map<String, Object> config = new HashMap<>();
            config.put("enabled", stats.isConversionEnabled());
            config.put("defaultInputFormat", stats.getDefaultInputFormat());
            config.put("defaultOutputFormat", stats.getDefaultOutputFormat());
            config.put("prettyPrint", stats.isPrettyPrint());
            config.put("validateInput", stats.isValidateInput());
            config.put("validateOutput", stats.isValidateOutput());
            config.put("maxConversionSize", stats.getMaxConversionSize());
            
            result.put("success", true);
            result.put("config", config);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取转换配置异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 测试数据格式转换
     * 
     * @param request 测试请求
     * @return 测试结果
     */
    @PostMapping("/test")
    public Map<String, Object> testDataFormatConversion(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String inputFormat = (String) request.get("inputFormat");
            String outputFormat = (String) request.get("outputFormat");
            
            if (inputFormat == null || outputFormat == null) {
                result.put("success", false);
                result.put("message", "缺少必要参数: inputFormat, outputFormat");
                return result;
            }
            
            // 生成测试数据
            String testData = generateTestData(inputFormat);
            
            // 执行转换
            DataFormatConverter.ConversionResult conversionResult = dataFormatConverter.convert(testData, inputFormat, outputFormat);
            
            result.put("success", conversionResult.isSuccess());
            result.put("testData", testData);
            result.put("convertedData", conversionResult.getData());
            result.put("status", conversionResult.getStatus());
            result.put("errorMessage", conversionResult.getErrorMessage());
            result.put("inputFormat", inputFormat);
            result.put("outputFormat", outputFormat);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "测试数据格式转换异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取转换器详细信息
     * 
     * @param key 转换器键
     * @return 转换器信息
     */
    @GetMapping("/converters/{key}")
    public Map<String, Object> getConverterInfo(@PathVariable String key) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<String> supportedConverters = dataFormatConverter.getSupportedConverters();
            
            if (supportedConverters.contains(key.toUpperCase())) {
                result.put("success", true);
                result.put("key", key);
                result.put("exists", true);
                result.put("description", "内置转换器");
            } else {
                result.put("success", true);
                result.put("key", key);
                result.put("exists", false);
                result.put("description", "转换器不存在");
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取转换器信息异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 生成测试数据
     * 
     * @param format 数据格式
     * @return 测试数据
     */
    private String generateTestData(String format) {
        switch (format.toUpperCase()) {
            case "JSON":
                return "{\"name\":\"测试用户\",\"age\":25,\"email\":\"test@example.com\",\"active\":true}";
            case "XML":
                return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><user><name>测试用户</name><age>25</age><email>test@example.com</email><active>true</active></user>";
            case "CSV":
                return "name,age,email,active\n测试用户,25,test@example.com,true";
            case "YAML":
                return "name: 测试用户\nage: 25\nemail: test@example.com\nactive: true";
            default:
                return "{\"message\":\"测试数据\"}";
        }
    }
}
